#include "client.h"


int main(int argc, char *argv[]){
    // ./client 192.168.14.9 1234
    ARGS_CHECK(argc,3);
    int sockFd = socket(AF_INET,SOCK_STREAM,0);
    ERROR_CHECK(sockFd,-1,"socket");
    struct sockaddr_in addr;
    addr.sin_family = AF_INET;
    addr.sin_port = htons(atoi(argv[2]));
    addr.sin_addr.s_addr = inet_addr(argv[1]);
    int ret = connect(sockFd,(struct sockaddr *)&addr,sizeof(addr));
    ERROR_CHECK(ret, -1, "connect");
    train_t train;
    int flag = 1;
    while(1) {
        if(1 == flag) {
            flag = 0; 
            int ret = login(sockFd);
            if(ret == -1) {
                break;
            }
            while(getchar()!='\n');
        }
        bzero(&train, sizeof(train));
        fgets(train.buf, sizeof(train.buf), stdin);
        char * p = strchr(train.buf, '\n');
        if(p!=NULL)
            *p = '\0';
        ret = cmsgdef(train.buf, &train);
        if(ret == -1)
        {
            puts("invalid cmd");
            continue;
        }
        send(sockFd, &ret, sizeof(int), MSG_NOSIGNAL);
        if(ret > 2) {
            switch(ret) {
                case 4:
                    //getsfile(sockFd, train.buf);
                    break;
                case 5:
                    //putsfile(sockFd, train.buf);
                    break;
                default:
                    send(sockFd, &train, sizeof(train.length)+train.length, MSG_NOSIGNAL);
                    break;
            }
        } else {
            bzero(&train, sizeof(train));
            int ret = msgprocess(sockFd, &train);
            if(ret == -1)
            {
                puts("connection close.");
                break;
            }
            puts(train.buf);
        }
    }
    close(sockFd);
}